package com.Logistics.pddispatch.execute;

import com.Logistics.pddispatch.entity.ScheduleJobBean;
import com.Logistics.pddispatch.entity.ScheduleJobLog;
import com.Logistics.pddispatch.service.impl.ScheduleJobLogServiceImpl;
import com.Logistics.mycommon.tools.IDAlgorithm;
import com.Logistics.mycommon.tools.SpringContextUtils;
import com.Logistics.pddispatch.utils.ExceptionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;

import static com.Logistics.pddispatch.utils.ScheduleUtils.JOB_PARAM_KEY;

public class ScheduleJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobBean scheduleJobBean = (ScheduleJobBean) context.getMergedJobDataMap().get(JOB_PARAM_KEY);

        System.out.println(new Date()+"定时任务开始执行------定时任务ID是"+scheduleJobBean.getId());

        //记录定时任务日志信息
        ScheduleJobLog scheduleJobLog = new ScheduleJobLog();
        scheduleJobLog.setId(new IDAlgorithm(0L,0L).nextIdAsString());
        scheduleJobLog.setJob_id(scheduleJobBean.getId());
        scheduleJobLog.setBean_name(scheduleJobBean.getBean_name());
        scheduleJobLog.setParams(scheduleJobBean.getParams());
        scheduleJobLog.setCreate_date(new Date());

        long startTime = System.currentTimeMillis();

        try {
            //通过反射调用智能调度方法
            //获取目标对象
            Object target = SpringContextUtils.getBean(scheduleJobBean.getBean_name());
            //获取方法
            Method method = target.getClass().getDeclaredMethod("run",String.class,String.class,String.class,String.class);
            //调用方法
            method.invoke(target, scheduleJobBean.getBusiness_id(),scheduleJobBean.getParams(),
                    scheduleJobBean.getId(),scheduleJobLog.getJob_id());
            scheduleJobLog.setStatus(1);
        }catch (Exception e){
            scheduleJobLog.setStatus(0);
            scheduleJobLog.setError(ExceptionUtils.getErrorStackTrace(e));
        }finally {
            int time = (int) (System.currentTimeMillis()-startTime);
            scheduleJobLog.setTimes(time);

            //保存日志信息
            ScheduleJobLogServiceImpl scheduleJobLogService = SpringContextUtils.getBean(ScheduleJobLogServiceImpl.class);
            scheduleJobLogService.save(scheduleJobLog);
        }
    }
}
